<template>
  <!-- 真警dialog-->
  <el-dialog
    title="真警"
    :visible="visible"
    @open="init"
    :before-close="resetFun"
    class="dialog-class1 true-warn-dialog"
    :destroy-on-close="true"
    width="560px"
  >
    <el-form
      ref="trueDialog"
      :model="ruleForm"
      :rules="rules"
      label-width="84px"
      v-loading="loading"
    >
      <el-form-item label="下一环节" prop="flowLink">
        <el-select
          v-model="ruleForm.flowLink"
          @change="getUserTree"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectDatas.nextLinkList"
            :key="item.value"
            :label="item.linkName"
            :value="item.linkId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        class="dealMan"
        label="处理人"
        v-if="selectDatas.nextLinkList.length > 0 && ruleForm.flowLink != 6"
        prop="userList"
      >
        <tree-select
          v-model="ruleForm.userList"
          :allUserTreeData="allUserTreeData"
          :userTreeData="userTreeData"
          node-key="id"
          default-expand-all
          show-checkbox
          ref="treeSelect"
          :config="{ label: 'userName', value: 'userId' }"
          :isShowAllBtn="isShowAllBtn"
          :isShowAllInfo.sync="isShowAllInfo"
          :nextLinkInfo="
            this.selectDatas.nextLinkList.find(
              (item) => item.curLink == this.ruleForm.flowLink
            )
          "
        />
      </el-form-item>
      <div class="position-info">
        <editUsefulWord
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></editUsefulWord>
      </div>
      <el-form-item label="研判说明" class="small" prop="desc">
        <el-input
          type="textarea"
          v-model="ruleForm.desc"
          resize="none"
          style="height: 60px"
          placeholder="请输入"
          size="small"
          maxlength="200"
        ></el-input>
      </el-form-item>
      <el-form-item v-show="isShowUsefulWord">
        <useful-word
          style="margin-top: -19px"
          :desc.sync="ruleForm.desc"
          :isShowUsefulWord.sync="isShowUsefulWord"
        ></useful-word>
      </el-form-item>
      <el-form-item>
        <FormItemIconTipLabel slot="label" />
        <EventFileUpload
          v-model="ruleForm.orderFileDTOList"
          :loading.sync="uploading"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="submitFun"
        type="primary"
        :loading="btnLoading || uploading"
        :disabled="selectDatas.nextLinkList.length === 0"
        >确 定</el-button
      >
      <el-button @click="resetFun">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { $getUrlParam } from "@/utils/public";
import {
  queryFlowLink,
  queryNextLink,
  checkAlarmOrder,
} from "@/api/modules/eventManagement/eventDialog/trueWarnDialog";
import { getFlow } from "@/api/modules/eventManagement/getFlowId";
import { getUserTree } from "@/api/modules/eventManagement/eventDispatch";
import TreeSelect from "@/components/TreeSelect";
import UsefulWord from "@/views/pages/eventManagement/eventDialog/usefulWord";
import editUsefulWord from "@/views/pages/eventManagement/eventDialog/editUsefulWord";
import EventFileUpload from "../components/EventFileUpload";
import FormItemIconTipLabel from "../components/FormItemIconTipLabel";
import { TR } from "@/utils/request";
export default {
  name: "trueWarnDialog",
  components: {
    TreeSelect,
    UsefulWord,
    editUsefulWord,
    EventFileUpload,
    FormItemIconTipLabel,
  },
  data() {
    return {
      ruleForm: {
        flowLink: "",
        desc: "",
        userList: "",
        orderFileDTOList: [],
      },
      flowId: "",
      flowTemplate: "",
      usersId: [],
      usersName: [],
      rules: {
        flowLink: [
          { required: true, message: "请选择流转环节", trigger: ["change"] },
        ],
        userList: [
          { required: true, message: "请选择人员", trigger: ["change"] },
        ],
        desc: [
          {
            validator: (rule, value, callback) => {
              if (value.length >= 200) {
                callback("字数请控制在200字符以内");
              } else {
                callback();
              }
            },
            trigger: ["blur"],
          },
        ],
      },
      selectDatas: {
        //下拉框数据
        nextLinkList: [],
        nameList: [],
      },
      userTreeData: [],
      allUserTreeData: [],
      loading: false,
      isTenantAdmin: this.$store.getters.userInfo.isTenantAdmin, // 1 租户管理员
      isShowAllBtn: true /** 是否显示全部处理人按钮 */,
      isShowAllInfo: false, // 是否显示全部处理人
      isShowUsefulWord: false, // 是否显示常用语列表
      btnLoading: false,
      uploading: false,
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    orderData: {
      type: Object,
      default: {},
    },
  },
  methods: {
    getUserId(curLink) {
      const _this = this;
      if (!_this.ruleForm.flowLink) {
        _this.ruleForm.userId = "";
      }
      let params = {
        flowId: _this.flowId,
        linkId: curLink,
        orgId: _this.orderData.orgRecord,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate,
      };
      queryFlowLink(params).then((res) => {
        if (res.code === 200) {
          let userName = res.data[0].userName.split(",");
          let userId = res.data[0].userId.split(",");
          let nameData = [];
          for (let i in userName) {
            nameData.push({
              userName: userName[i],
              userId: userId[i],
            });
          }
          _this.selectDatas.nameList = nameData;
        }
      });
      // $v.post(_this, urlNewAr + '/flow/alarm/queryFlowLink',params, function (res) {
      //   if (res.code === 200) {
      //     let userName = res.data[0].userName.split(",");
      //     let userId = res.data[0].userId.split(",");
      //     let nameData = [];
      //     for( let i in userName){
      //       nameData.push({
      //         'userName':userName[i],
      //         'userId':userId[i]
      //       })
      //     }
      //     _this.selectDatas.nameList = nameData;
      //   }
      // });
    },
    getUserName(ids) {
      this.usersId = [];
      this.usersName = [];
      let selectInfo = {};
      for (let i in ids) {
        selectInfo = this.selectDatas.nameList.find(
          (item) => item.userId == ids[i]
        );
        this.usersId.push(selectInfo.userId);
        this.usersName.push(selectInfo.userName);
      }
    },
    async selectNextLinkList() {
      const _this = this;
      let params = {
        curLink: _this.orderData.linkId,
        flowId: _this.flowId,
        warningSource: _this.orderData.warningSource,
        templateId: _this.orderData.flowTemplate,
      };
      const res = await queryNextLink(params);
      if (res.code === 200) {
        _this.selectDatas.nextLinkList = res.data;
        if (
          _this.selectDatas.nextLinkList &&
          _this.selectDatas.nextLinkList.length == 1
        ) {
          _this.ruleForm.flowLink = res.data[0].linkId;
          // this.isShowAllBtn = res.data[0].dataFilterPermiss === '0' && res.data[0].customAdmin === '1';
          this.getUserTree(_this.ruleForm.flowLink);
        }
      } else {
        $message.warning(res.msg);
      }
    },
    getFlowIds(tenantId, warningSource, alarmCode) {
      const _this = this;
      getFlow({
        tenantId: tenantId,
        warningSource: warningSource,
        alarmCode: alarmCode,
      }).then((resp) => {
        if (resp.code == 200) {
          let flowFlow = tenantId + "_" + warningSource;
          // flowId = resp.data.flowId;
          _this.flowId = resp.data[flowFlow];
          _this.flowTemplate = _this.orderData.flowTemplate
            ? _this.orderData.flowTemplate
            : _this.flowId;
        } else {
          console.log("");
        }
      });
    },
    async init() {
      this.loading = false;
      this.btnLoading = false;
      const _this = this;
      _this.flowTemplate = _this.orderData.flowTemplate;
      if (!_this.orderData.flowId) {
        _this.getFlowIds(
          _this.orderData.tenantId,
          _this.orderData.warningSource,
          _this.orderData.warningTypeId
        );
      } else {
        _this.flowId = _this.orderData.flowId;
      }
      await this.selectNextLinkList();
      // let params = {
      //   'flowId':31,
      //   'curLink':2
      // };
      // queryNextLink(params).then(res => {
      //   if (res.code === 200) {
      //     // debugger
      //     _this.selectDatas.nextLinkList = res.data;
      //   }
      // });
      // $v.post(_this, urlNewAr + '/flow/alarm/queryNextLink',params, function (res) {
      //   if (res.code === 200) {
      //     // debugger
      //     _this.selectDatas.nextLinkList = res.data;
      //   }
      // });
    },
    // openFunc() {
    //   this.init();
    // let _this = this;
    // //事件等级
    // $v.post(_this, urlSystem + '/system/getEnumInfo', {enumTypeId: 41}, function (result) {
    //     if (result.resultStat === "SUCCESS") {
    //       _this.selectDatas.gradeList = result.data.list;
    //     }
    //   }
    // )
    // },
    //提交
    async submitFun() {
      let _this = this;
      // if (_this.ruleForm.desc.length > 200) {
      //   _this.$message.warning("研判说明不能超过200字！");
      //   return;
      // }
      const [err] = await TR(this.$refs.trueDialog.validate());
      if (err) {
        return;
      }

      const target = _this.selectDatas.nextLinkList.find(
        (item) => item.curLink == _this.ruleForm.flowLink
      );
      const angle =
        this.orderData.horiAzimuthAngle || this.orderData.horiAzimuthAngle === 0
          ? this.orderData.horiAzimuthAngle
          : null;
      let params = {
        ...target,
        flowId: target.flowId,
        flowTemplate: _this.flowTemplate,
        linkName: target.linkName,
        linkId: target.curLink,
        timeLimit: target.timeLimit,
        isSign: target.signFlag,
        userType: target.userType,
        msgNotifyType: target.msgNotifyType,
        orderId: _this.orderData.warningOrderId,
        warningOrderId: _this.orderData.warningOrderId,
        horiAzimuthAngle: angle,
        orderStatus: "2", //0-假警、2-真警、7-重复报警
        remark: _this.ruleForm.desc, //告警说明
        checkMan: _this.$store.getters.userInfo.userId, //研判人员ID
        duplicateOrderId: "", //重复的告警单ID，重读告警时必填
        enableAcceptanceMode: this.orderData.enableAcceptanceMode, // 当前事件受理状态（0：不开启 1：开启（待受理）2：已受理 3：受理完成）
        timeLimitAcceptance: target.timeLimitAcceptance, // 下一环节受理时限
        attrId: target.attrId, // 下一环节流程环节id
        nextEnableAcceptanceMode: target.enableAcceptanceMode, // 下一环节受理状态
        devicePitch: this.orderData.devicePitch, // 俯仰角
        alarmReason: this.orderData.alarmReason, // 告警原因
        deviceHorizontal: this.orderData.deviceHorizontal, // 水平角
        orderFileDTOList: this.ruleForm.orderFileDTOList, // 附件
      };

      // params.linkId = _this.ruleForm.flowLink;
      params.isNextLink = "1";
      // params.isSign = '1';
      params.processDTOList = [];
      for (let i in _this.usersName) {
        params.processDTOList.push({
          processId: _this.usersId[i],
          processName: _this.usersName[i],
          groupId: "",
        });
      }
      if (_this.orderData.emergencyLevel != "") {
        params["emergencyLevel"] = _this.orderData.emergencyLevel; //告警等级,AI告警时必传
      }
      if (_this.orderData.warningTypeId != "") {
        params["warningTypeId"] = _this.orderData.warningTypeId;
      }
      if (_this.orderData.provinceId != "") {
        params["provinceId"] = _this.orderData.provinceId;
        params["cityId"] = _this.orderData.cityId;
        params["countyId"] = _this.orderData.countyId;
      }
      if (_this.orderData.longitude != "0") {
        params["longitude"] = _this.orderData.longitude;
        params["latitude"] = _this.orderData.latitude;
      }
      if (this.orderData.updateAddress) {
        params.gridId = this.orderData.gridId;
        params.gridName = this.orderData.gridName;
        params.horiAzimuthAngle = this.orderData.horiAzimuthAngle;
        params.checkGridFlag = "1"; // 是否修改网格员  1 是  0 否
      } else {
        params.checkGridFlag = "0";
      }
      params["address"] = _this.orderData.address;
      if (this.ruleForm.flowLink != "6") {
        // 有下一环节
        if (!this.ruleForm.userList || this.ruleForm.userList.length === 0) {
          return;
        }
        params.realLinkType = this.selectDatas.nextLinkList.filter(
          (item) => item.linkId == this.ruleForm.flowLink
        )[0].realLinkType;
        params.flowLinkType = "0";
        params.processDTOList = this.ruleForm.userList.map((ele) => ({
          processId: ele.userId,
          processName: ele.userName,
        }));
      } else {
        // 下一环节为完结
        params.realLinkType = "6";
        params.flowLinkType = "0";
        params.processDTOList = [];
      }

      this.btnLoading = true;
      checkAlarmOrder(params).then((resp) => {
        this.btnLoading = false;
        let msgId = {
          id: this.orderData.warningOrderId,
          status: this.orderData.orderStatus,
        };
        this.$store.dispatch("closeSocketMsg", msgId);
        if (resp && resp.code == 200) {
          $message.success("研判成功");
          let userId = this.$store.getters.userInfo.userId;
          if (
            ((Array.isArray(this.ruleForm.userList) &&
              this.ruleForm.userList.find((item) => item.userId == userId)) ||
              this.isTenantAdmin == "1") &&
            this.ruleForm.flowLink != "6"
          ) {
            // this.$close(); // 有下一环节处理权限就自动打开下一环节
            this.$store.dispatch("tagsView/delView", this.$route);
            this.refreshSelectedTag(this.$route, params.realLinkType);
          } else {
            _this.onSuccess();
          }
          _this.resetForm();
        } else {
          $message.warning(resp.msg);
        }
      });
      _this.$emit("update:visible", false);
    },
    onSuccess() {
      const url =
        $getUrlParam("pageType") === "false"
          ? "/eventManagement"
          : "/eventManagement/myEvent";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push(url);
    },
    refreshSelectedTag(view, realLinkType) {
      this.$store.dispatch("tagsView/delCachedView", view).then(() => {
        let { fullPath } = view;
        fullPath = this.replaceParamVal(fullPath, "orderStatus", realLinkType);
        this.$nextTick(() => {
          this.$router.replace({
            path: "/redirect" + fullPath,
          });
        });
      });
    },
    replaceParamVal(oUrl, paramName, replaceWith) {
      var re = eval("/(" + paramName + "=)([^&]*)/gi");
      var nUrl = oUrl.replace(re, paramName + "=" + replaceWith);
      return nUrl;
    },
    resetFun() {
      this.resetForm();
      this.isShowAllBtn = false; /** 是否显示全部处理人按钮 */
      this.isShowAllInfo = false; // 是否显示全部处理人
      this.isShowUsefulWord = false; // 是否显示常用语列表
      this.$emit("update:visible", false);
    },
    resetForm() {
      this.ruleForm = {
        flowLink: "",
        desc: "",
        userList: "",
      };
      this.userTreeData = [];
      this.allUserTreeData = [];
    },
    transferTreeData(list) {
      return list.map((node) => {
        const { nodeId, ...rest } = node;
        let nodeName = node.userName || node.nodeName;
        const obj = {
          id: nodeId,
          label: nodeName,

          ...rest,
        };
        if (node.children) {
          return {
            ...obj,
            children: this.transferTreeData(node.children),
          };
        }
        return obj;
      });
    },
    getUserTree(linkParam) {
      if (linkParam == "6") {
        return;
      }
      const selectLinkData = this.selectDatas.nextLinkList.filter(
        (item) => item.linkId === linkParam
      );
      this.isShowAllBtn = !(
        selectLinkData[0].dataFilterPermiss === "0" &&
        selectLinkData[0].customAdmin === "1"
      );
      this.isShowAllInfo =
        selectLinkData[0].dataFilterPermiss === "0" && !this.isShowAllBtn;
      this.ruleForm.userList = [];
      this.$set(this.ruleForm, "userList", []);
      const params = {
        curLink: linkParam,
        tenantId: this.$store.getters.userInfo.tenantId
          ? this.$store.getters.userInfo.tenantId
          : this.orderData.tenantId,
        flowId: this.orderData.flowId,
        deviceCode: this.orderData.deviceCode,
        provinceId: this.orderData.provinceId,
        cityId: this.orderData.cityId,
        countyId: this.orderData.countyId,
        warningSource: this.orderData.warningSource,
        gridId: this.orderData.gridId,
        warningTypeId: this.orderData.warningTypeId,
      };
      this.loading = true;
      getUserTree(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.userTreeData = this.transferTreeData([res.data.sysPowerInfo]);
          this.allUserTreeData = this.transferTreeData([res.data.sysAllInfo]);
          this.userTreeData[0].root = 1;
          this.allUserTreeData[0].root = 1;
          this.$nextTick(() => {
            this.$refs.treeSelect.checkTreeChange();
          });
        }
      });

      // this.dataList = [];
      // this.generateList(this.userTreeData);
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-dialog__body {
  text-align: center;
  padding: 12px 52px 0;
}
/deep/ .el-row {
  margin-bottom: 1.5%;
}
/deep/ .el-upload--picture-card {
  border-radius: 5px;
}
/deep/ .el-form-item__error {
  position: relative;
}
/deep/ .submitClass {
  background: #ff6a6c !important;
  color: #ffffff !important;
}
/deep/ .el-select__tags {
  overflow: auto;
  .el-tag.el-tag--info {
    max-width: 80%;
  }
}
/deep/.el-form-item__error {
  text-align: left;
}
.position-info {
  margin-top: -10px;
  padding-right: 5px;
  //margin-bottom: 5px;
}
.dialog-class1 {
  /deep/.el-dialog > .el-dialog__header {
    padding: 12px;
    height: 48px;
  }
  /deep/.el-dialog {
    border-radius: 4px;
  }
  /deep/ .el-form-item--mini.el-form-item,
  .el-form-item--small.el-form-item {
    margin-bottom: 12px;
  }
  /deep/ .el-textarea__inner {
    height: 60px;
  }
  /deep/ .el-dialog > .el-dialog__footer {
    padding: 12px;
    height: 56px;
  }
  /deep/ .el-button.el-button--small {
    height: 32px;
    border-radius: 4px;
  }
  /deep/ .el-button + .el-button {
    margin-left: 8px;
  }
  /deep/ .el-form-item .el-form-item__label {
    padding-right: 9px;
  }
  /deep/ .el-form-item {
    .el-form-item__content {
      .commonTreeSelect {
        height: 32px;
        .el-select {
          .el-input--medium .el-input__inner {
            height: 32px;
            line-height: 32px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.true-warn-dialog {
  .el-select__tags,
  .el-select__tags-text {
    max-width: 225px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .el-tag {
    display: flex;
    align-items: center;
    .el-tag__close {
      min-width: 16px;
    }
  }
  .el-select .el-select__tags > span {
    display: flex;
    width: 100%;
    align-items: center;
  }
}
</style>
